<?php
namespace app\app\controller;

use app\common\model\Baby;
use app\common\model\Parents;
use think\Cache;

class Site extends Base
{
    /**
     * 注册
     * @return \think\response\Json
     */
    public function register()
    {
        try{
            $input = input('post.',null,'trim');
            $parent = Parents::where(['mobile'=>$input['mobile']])->find();
            if(empty($parent)){
                $parent = new Parents();
            }
            $validate_code = SendCode::validateMobileCode($input['mobile'],$input['code']);
            if($validate_code['code'] == 0){
                exception($validate_code['msg']);
            }
            if($parent->allowField(true)->force()->save($input) === false){
                exception('保存失败');
            };
            Cache::rm('xcx_sms_code_'.$input['mobile']);
            $parent['baby_num'] = Baby::where(['parent_id'=>$parent['id']])->count();
            $default_baby = Baby::get(['parent_id'=>$parent['id'],'is_default'=>1]);
            $parent['baby_default_id'] = !empty($default_baby)?$default_baby['id']:'';
            return $this->succeed('操作成功',['user'=>$parent]);
        }catch (\Exception $e){
            return $this->fail($e->getMessage());
        }

    }

    /**
     * 获取token
     * @return \think\response\Json
     */
    public function token()
    {
        $input = input('','','trim');
        if(isset($input['name']) && $input['name']=='CHENGzhang921' && isset($input['password']) && $input['password'] == 'wadFwSrsr'){
            return $this->succeed('',['token'=>base64_encode('chengzhangxcx'),'secret'=>config('xcx_config.secret')]);
        }else{
            return $this->fail('无权限访问');
        }
    }



    /**
     *根据code获取openid
     * @return \think\response\Json
     */
    public function openid()
    {
        try{
            $request = input('','','trim');
            if(isset($request['name']) && $request['name']=='CHENGzhang921' && isset($request['password']) && $request['password'] == 'wadFwSrsr'){
                $url = 'https://api.weixin.qq.com/sns/jscode2session';
                $input['js_code'] = input('code');
                $input['appid'] = config('xcx_config.appid');
                $input['secret'] = config('xcx_config.secret');
                $input['grant_type'] = 'authorization_code';

                $data = $this->curl_request($url,$input);
                $data_array = json_decode($data,true);
                if(isset($data_array['errcode'])){
                    return $this->fail($data_array['errmsg']);
                }
                $parent = Parents::where(['openid'=>$data_array['openid']])->find();
                if(!empty($parent)){
                    //已注册
                    $parent['baby_num'] = Baby::where(['parent_id'=>$parent['id']])->count();
                    $default_baby = Baby::get(['parent_id'=>$parent['id'],'is_default'=>1]);
                    $parent['baby_default_id'] = !empty($default_baby)?$default_baby['id']:'';
                    return $this->succeed('',['parent'=>$parent,'openid'=>$data_array['openid'],'token'=>base64_encode('chengzhangxcx'),'secret'=>config('xcx_config.secret')]);
                }else{
                    //未注册
                    return $this->succeed('',['openid'=>$data_array['openid'],'token'=>base64_encode('chengzhangxcx'),'secret'=>config('xcx_config.secret')]);
                }

            }else{
                return $this->fail('无权限访问');
            }



        }catch (\Exception $e){
            return $this->fail($e->getMessage());
        }

    }



    //参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
    function curl_request($url,$post='',$cookie='', $returnCookie=0){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
//        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        curl_setopt($curl, CURLOPT_REFERER, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER , false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST  , false);
        if($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if($returnCookie){
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie']  = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        }else{
            return $data;
        }
    }
}
